﻿using System;
using System.Collections.Generic;

using zijian666.Converts.Abstractions;
using zijian666.Converts.Core;

//using System.Runtime.Remoting;

namespace zijian666.Converts.Dynamic;

/// <summary>
/// 基于 <seealso cref="object"/> 的动态类型
/// </summary>
internal class DynamicEntity : DynamicObjectBase<object>
{
    /// <summary>
    /// 反射属性集合
    /// </summary>
    private readonly PropertiesCollection _properties;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="value"></param>
    /// <param name="convertSettings"></param>
    public DynamicEntity(object value, IConvertSettings convertSettings)
        : base(value, convertSettings)
    {
        if (value is null)
        {
            throw new ArgumentNullException(nameof(value));
        }

        _properties = PropertyHelper.GetByType(value.GetType());
    }

    /// <inheritdoc />
    public override IEnumerable<string> GetDynamicMemberNames() => _properties.Keys;

    /// <inheritdoc />
    protected override object? this[string name]
    {
        get
        {
            var p = _properties[name];
            if (p is null)
            {
                return null;
            }
            return p.GetValue(Value!, ConvertSettings.ReflectCompiler);
        }
        set
        {
            var p = _properties[name];
            if (p is null)
            {
                return;
            }
            if (!p.PropertyType.IsInstanceOfType(value))
            {
                value = value.Convert(p.PropertyType, ConvertSettings).Value;
            }
            p.SetValue(Value!, value, ConvertSettings.ReflectCompiler);
        }
    }
}
